package com.xiaoran.robot.config;
import com.alibaba.fastjson.JSONObject;
import com.xiaoran.robot.utils.MessageParser;
import com.xiaoran.robot.utils.StringUtils;
import com.xiaoran.robot.utils.ThreadLocalUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MyWebsocketClient extends WebSocketClient {
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            2,
            4,
            30,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(2),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.DiscardOldestPolicy()
    );

    public MyWebsocketClient(URI serverUri) {
        super(serverUri);
    }
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("消息监听开始");
    }

    @Override
    public void onMessage(String s) {
        threadPoolExecutor.execute(()->{
            JSONObject jsonData = StringUtils.toJson(s);
            new ThreadLocalUtils().setMsg(jsonData);
            MessageParser instance = new MessageParser(jsonData);
            instance.parseMessage();
        });
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        System.out.println(s);
        System.out.println("消息监听结束，线程池关闭");
        threadPoolExecutor.shutdown();
    }

    @Override
    public void onError(Exception e) {
        System.out.println(e.toString());
        System.out.println("错误");
    }
}
